package com.windchime.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Friend;
import com.windchime.blog.entity.vo.FriendSearch;
import com.windchime.blog.mapper.FriendMapper;
import com.windchime.blog.service.FriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 友链表 服务实现类
 * </p>
 *
 * @author WindChime
 * @since 2021-08-02
 */
@Service
public class FriendServiceImpl extends ServiceImpl<FriendMapper, Friend> implements FriendService {

    /**
     * 保存友链
     * @param friend 友链
     * @return true
     */
    @Override
    public boolean saveFriend(Friend friend) {
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();
        wrapper.eq("name", friend.getName());
        Friend has_friend = baseMapper.selectOne(wrapper);
        if (has_friend == null) {
            return baseMapper.insert(friend) > 0;
        }
        return false;
    }

    /**
     * 分页查询带条件
     * @param page      当前页
     * @param limit     当前页条目数
     * @param friendSearch 条件
     * @return friends
     */
    @Override
    public PageInfo<Friend> selectFriendList(Integer page, Integer limit, FriendSearch friendSearch) {
        PageHelper.startPage(page, limit);
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        if (!StringUtils.isEmpty(friendSearch.getName())) {
            wrapper.like("name", friendSearch.getName());
        }
        if (!StringUtils.isEmpty(friendSearch.getSex())) {
            wrapper.eq("sex", friendSearch.getSex());
        }
        List<Friend> friends = baseMapper.selectList(wrapper);
        return new PageInfo<>(friends);
    }

    /**
     * 修改友链
     * @param friend 友链
     * @return true
     */
    @Override
    public boolean editFriend(Friend friend) {
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();

        wrapper.notIn("id", friend.getId());
        List<Friend> tags = baseMapper.selectList(wrapper);
        List<String> friendNames = tags.stream().map(Friend::getName).collect(Collectors.toList());

        if (!friendNames.contains(friend.getName())) {
            return baseMapper.updateById(friend) > 0;
        }

        return false;
    }
}
